public class HashTable<K,V> {
    public static class Node<K,V> {
        private K key;
        private V val;
        private Node<K,V> next;

        public Node(K key,V val) {
            this.key = key;
            this.val = val;
        }

    }
    private Node<K,V>[] array;
    private int usedSize;
    private static final double loadFactor = 0.75;//负载因子
    public HashTable() {
        this.array = (Node<K, V>[]) new Node[10];
        this.usedSize = 0;
    }

    public void put(K key,V val) {
        //通过hashCode方法 定义数组下标
        int hash = key.hashCode();
        int index = hash%this.array.length;
        //判断index位置是否存在key
        Node<K,V> cur = this.array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node<K,V> node = new Node<>(key,val);
        node.next = this.array[index];
        this.array[index] = node;
        this.usedSize++;
        //大于负载因子就增容
        if (loadFactor() >= loadFactor) {
            resize();
        }
    }
    public double loadFactor() {
        return  this.usedSize*1.0 / this.array.length;
    }

    /**
     * 2倍扩容
     */
    public void resize() {
        Node<K,V>[] arr = new Node[this.array.length*2];
        for (int i = 0; i < this.array.length; i++) {
            Node<K, V> cur = this.array[i];
            Node<K, V> curNext = null;
            while (cur != null) {
                curNext = cur.next;
                int hash = cur.key.hashCode();
                int index = hash % arr.length;
                cur.next = arr[index];
                arr[index] = cur;
                cur = curNext;
            }
        }
        this.array = arr;
    }
    public V get(K key) {
        if (this.usedSize == 0) {
            throw new NullPointerException("哈希表为空");
        }
        int index = key.hashCode()%this.array.length;
        Node<K,V> cur = this.array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
